﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Catchbase.TestTools.UTest
{
    /// <summary>
    /// A file containing your passwords nessecary for running acceptance-tests. This file should not be checked in.
    /// contents (UTF-8):
    /// google-Username
    /// google-Password
    /// catchbase-username
    /// url-home 
    /// secret shared key
    /// </summary>
    public class SecretSettings
    {
        private readonly string _secretSettingsFile;
        private readonly Dictionary<string,string> _sectretDictionary = new Dictionary<string, string>();

        public SecretSettings(string secretSettingsFile)
        {
            _secretSettingsFile = secretSettingsFile;
            ReadSecrets();
        }

        public string GoogleUsername
        {
            get { return ReadValue("google-Username"); }
        }

        public string GooglePassword
        {
            get { return ReadValue("google-Password"); }
        }

        public string CatchbaseUsername
        {
            get { return ReadValue("catchbase-Username"); }
        }

        public string UrlHome
        {
            get { return ReadValue("Url-home"); }
        }

        public string SharedSecret
        {
            get { return ReadValue("SharedSecret"); }
        }

        private string ReadValue(string key)
        {
            if (!_sectretDictionary.ContainsKey(key))
                throw new KeyNotFoundException(KeyNotFoundExceptionMessage(key));
            return _sectretDictionary[key];
        }

        private void ReadSecrets()
        {
            if (!File.Exists(_secretSettingsFile)) throw new FileNotFoundException(FileNotFoundExceptionMessage);
            var lines = File.ReadAllText(_secretSettingsFile).Split(new[] { "\r\n" }, StringSplitOptions.None);
            if (lines.Length == 0) throw new FileLoadException(FileLoadExceptionMessage);
            foreach (var pair in lines.Select(line => line.Split(new[] {"\t"}, StringSplitOptions.None)))
            {
                if (pair.Length != 2) throw new FileLoadException(FileLoadExceptionMessage);
                _sectretDictionary.Add(pair[0], pair[1]);
            }
        }
        
        private string FileNotFoundExceptionMessage
        {
            get { return string.Format("Could not find {0}.", _secretSettingsFile); }
        }

        private string FileLoadExceptionMessage
        {
            get { return string.Format("Error parsing file, is {0} saved as UTF-8?", _secretSettingsFile); }
        }

        private string KeyNotFoundExceptionMessage(string key)
        {
            return string.Format("Could not find value of {0} in secret settings file {1}.", key, _secretSettingsFile);
        }
    }
}